#!/usr/bin/perl -w

use strict;

use lib "./lib";
use CGI;
use URI::Escape;
use HTML::Template;
use String::Random;
use DB::MailAccounts;

&main();

sub main() {
	my $q = new CGI;
	my $template = "../templates/delete.tmpl";
	my $tmpl = new HTML::Template(filename => $template);


    my $yes = $q->param("yes");
    my $no = $q->param("no");
    my $email = $q->param("e");
    my $secret = $q->param("s");

    if ($no) { 
        print $q->redirect("/cgi-bin/index.cgi");
    }
    elsif ($yes) {
        if (&validate_email_account($email, $secret)) {
            # delete email account
            $tmpl->param(unregistered => 1);
        }
        else {
            $tmpl->param(invalid => 1);
        }
    } 
    else {
        # todo: if email_account doesn't exist
        $tmpl->param(email => $email);
        $tmpl->param(secret => $secret);
    }

	print $q->header(-type => 'text/html', -charset => 'utf-8');
	print $tmpl->output;

}

sub validate_email_account {
    my ($email, $secret) = @_;

    if ($email and $secret) {
        my $db = DB::MailAccounts->new(); 
        my $rh_account = $db->get_account_by_mail_secret($email, $secret);
        if ($rh_account) {
            return 1;
        }
    }
    return 0;
}

